package com.bckj.fastboot.core.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ClassScanner {
    
    public static List<Class<?>> getClassesInPackage(String packageName) throws IOException, ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<>();
        // 创建资源模式解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 创建元数据读取器工厂
        MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resolver);
        
        // 将包名转换为类路径匹配模式
        String packagePath = "classpath*:" + 
                            ClassUtils.convertClassNameToResourcePath(packageName) + 
                            "/**/*.class";
        // 获取所有匹配的资源
        Resource[] resources = resolver.getResources(packagePath);
        
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                // 通过 MetadataReader 读取类元数据，避免直接加载类
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                // 使用 Class.forName 加载类，确保在各类环境中都能正确加载
                Class<?> clazz = Class.forName(className);
                classes.add(clazz);
            }
        }
        return classes;
    }
}